package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStats;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.IUserSerivce;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class IUserSerivceImpl extends ServiceImpl<UserMapper, User> implements IUserSerivce {

    private UserMapper userMapper;

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
//        查询用户
        User user = this.getById(id);//  此类已经继承了ServiceImpl所以直接可以调用它本身的getById()方法
//        校验用户状态
        if (user == null || user.getStatus() == UserStats.FROZEW) {
            throw new RuntimeException("用户状态异常");
        }
//        校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }
//        扣减余额(更改状态)
        userMapper.deductBalance(id, money);
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                /*
                 * 这里的状态改不了!!!!
                 * */
                .set(remainBalance <= 0, User::getStatus, UserStats.FROZEW)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())   //乐观锁
                .update();  //执行方法
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        User user = this.getById(id);
        if (user == null || user.getStatus() == UserStats.FROZEW) {
            throw new RuntimeException("用户状态异常");
        }
//        查询地址（使用静态方法）
        List<Address> address = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
//        封装
//        User转userVO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
//        转换地址VO
        if (CollUtil.isNotEmpty(address)) {
            userVO.setAddresses(BeanUtil.copyToList(address, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
//        查询用户
        List<User> users = this.listByIds(ids);
        if (CollUtil.isEmpty(users)) {  //如果users集合为空或者为null
            return Collections.emptyList(); //返回一个空集合
        }
//        将所有的用户id获取出来
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
//        根据用户id查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
//        将地址转换我为VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
//        用户地址集合分组处理，相同用户的放入一个集合（组）中
        Map<Long, List<AddressVO>> addressMap = new HashMap<>();
        if (CollUtil.isNotEmpty(addresses)) {
            addressMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
//        转换VO返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
//            转换User的PO为VO
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            list.add(userVO);
            userVO.setAddresses(addressMap.get(user.getId()));
        }
        return list;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery query) {
        String name = query.getName();
        Integer status = query.getStatus();
//        构建分页条件
        Page<User> page = query.toMpPageDefaultSortByUpdateTime();

//        分页查询
        Page<User> p = lambdaQuery().
                like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

//        3、封装VO结果
//        return PageDTO.of(p,UserVO.class);

        //第二种封装VO
        return PageDTO.of(p, user -> {
//            拷贝基础属性
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
//            处理特殊属性
            vo.setUsername(vo.getUsername().substring(0,vo.getUsername().length()-2)+"**");
            return vo;
        });
    }
}
